<?php
/**
 * Created by xuan.
 * Author: xuan
 * Date: 2018/8/3
 * Time: 18:24
 */
namespace app\api\controller\v1;

use app\api\model\Goodsorder as GoodsorderModel;
use app\api\model\Member as MemberModel;
use app\api\model\Goods as GoodsModel;
use app\api\model\Address as AddressModel;
use think\Request;
use app\api\controller\BaseController;
use common\util\Tools;
use app\common\service\NoticeService;
use app\common\service\MsgService;
use app\common\model\GoodsSpecModel;
use app\common\model\GoodsSpecGoodsPriceModel;

class Goodsorder extends BaseController {

    /*
     * 初始化操作
     */
    public function _initialize() {
        $this->needLogin();
    }

    /**
     * 添加
     */
    public function add() {
        if (request()->isPost()) {
            $all = Request::instance()->param();
            $mid = $this->getLoginId();
            $all['mid'] = $mid;
            if (empty($all['goodsid'])) {
                return $this->returnResult(- 6, '产品必须选择!');
            } elseif (empty($all['courier_num'])) {
                return $this->returnResult(- 6, '产品个数必须选择!');
            }
            if (empty($all['beizhu'])) {
                $all['beizhu'] = "";
            }
            $num = $all['courier_num'];
            if ($num <= 0 || $num > 10000) {
                return $this->returnResult(- 2, '选择的产品数量不正确!');
            }

            $times = time();
            $all['oid'] = $all['mid'] . $times;
            $send_addr_id = $this->request->param('send_addr_id', 0); // 发送默认地址
            $receive_addr_id = $this->request->param('receive_addr_id', 0); // 接受默认地址
            $key = $this->request->param('key', ''); // 选中规格
            
            if (empty($receive_addr_id)) {
                return $this->returnResult(- 2, '发货地址没有选择!');
            }
            $all['send_addr_id'] = $send_addr_id;
            $all['receive_addr_id'] = $receive_addr_id;

            $data_member = MemberModel::selectOneMemberByID($all['mid']);
            if ($data_member) {
                $data_members = $data_member->toArray();
                $all['mtel'] = $data_members['tel'];
                $all['fid'] = $data_members['fid'];
            } else {
                return $this->returnResult(- 2, '无权限!');
            }

            $goodsId = $all['goodsid'];

            $data_goods = GoodsModel::selectOneGoodsByID($goodsId);
            if (empty($data_goods)) {
                return $this->returnResult(- 2, '产品不存在!');
            }
            if ($data_goods['goods_type_id'] && empty($key)) {
                return $this->returnResult(- 2, '请选择规格!');
            }
            $keyName = '';
            if ($key) {
                $goodsSpac = GoodsSpecGoodsPriceModel::where('goods_id', $goodsId)->where('key', $key)->find();
                if(empty($goodsSpac)){
                    return $this->returnResult(- 2, '请选择正确规格!');
                }
                $data_goods['stock'] = $goodsSpac['store_count']; // 重置库存
                $keyName = $goodsSpac['key_name'];
            }
            $all['key'] = $key;
            $all['key_name'] = $keyName;
            
            if ($data_goods['stock'] < $num) {
                return $this->returnResult(- 2, '库存不足!');
            }

            $start_time = $data_goods['start_time'];
            $end_time = $data_goods['end_time'];
            $time = time();
            if ($data_goods['is_time_limit']) { // 限时产品
                if ($start_time > 0 && $time < $start_time) {
                    return $this->returnResult(- 2, '还没开始哈,不能下单!');
                }
                if ($end_time > 0 && $end_time < $time) {
                    return $this->returnResult(- 2, '已经结束啦!');
                }
            }

            if ($data_goods) {
                $all['goodsname'] = $data_goods['goodsname'];
                $all['sigprice'] = $data_goods['price'];
                $all['total'] = $all['sigprice'] * $all['courier_num'];
                $all['reward'] = $data_goods['reward'];
                $all['pic'] = $data_goods['pic'];
                $all['store_id'] = $data_goods['store_id'];
            } else {
                return $this->returnResult(- 2, '选中的产品有误!');
            }

            $balance = $data_members['account'] + $data_members['rewardaccount'];
            $total = $all['total'];

            if ($balance < $total) {
                return $this->returnResult(- 8, '账户余额不足，请充值!');
            }

            $data_address = AddressModel::instance()->find($receive_addr_id);
            if ($data_address) {
                $data_addresss = $data_address->toArray();
                $all['receive_name'] = $data_addresss['name'];
                $all['receive_tel'] = $data_addresss['tel'];
                $all['addrvalue'] = $data_addresss['addrvalue'];
                $all['receive_addr'] = $data_addresss['addr'];
            } else {
                return $this->returnResult(- 3, '请选择收货地址!');
            }
            $needRewardAccount = 0;
            $needAccount = $total;
            if ($total > $data_members['account']) {
                $needRewardAccount = $total - $data_members['account'];
                $needAccount = $data_members['account'];
            }
            $all['account'] = $needAccount;
            $all['reward_account'] = $needRewardAccount;

            $data = GoodsorderModel::addOneGoodsorder($all);
            if ($data) {
                // 减少余额账号,增加余额锁定账号,减少奖励账户,增加奖励锁定账号
                MemberModel::instance()->where('id', $mid)
                    ->dec('account', $needAccount)
                    ->inc('account_lock', $needAccount)
                    ->dec('rewardaccount', $needRewardAccount)
                    ->inc('rewardaccount_lock', $needRewardAccount)
                    ->update();
                // 更新规格库存
                $key && GoodsSpecGoodsPriceModel::where('goods_id', $goodsId)->where('key', $key)
                    ->dec('store_count', $num)
                    ->update();
                GoodsModel::instance()->where('id', $goodsId)
                    ->inc('sales', $num)
                    ->dec('stock', $num)
                    ->update();
            }
            if ($data) {
                if ($data_member['openid']) {
                    $goodsname = $all['goodsname'];
                    if($keyName){
                        $goodsname .= $keyName;
                    }
                    MsgService::sendOrderPayMsg($data_member['openid'], $data['id'], $all['oid'],$goodsname , $all['total'], $all['receive_name'], $all['receive_tel']);
                }
                return $this->returnResult(1, '下单成功!', $data);
            } else {
                return $this->returnResult(- 2, '下单失败!');
            }
        } else {
            return $this->returnResult(- 1, '下单失败!');
        }
    }

    /**
     * 列表
     */
    public function lists() {
        if (request()->isPost()) {
            $length = 10;

            $all = Request::instance()->param();

            $mid = $this->getLoginId();
            $all['mid'] = $mid;

            // if(empty($all['start'])){ $start = 0; }else{ $start = trim($all['start']); }
            if (empty($all['draw'])) {
                $draw = 1;
            } else {
                $draw = trim($all['draw']);
            }

            if (empty($all['ispay'])) {
                $ispay = 0;
            } else {
                $ispay = trim($all['ispay']);
            }

            $start = ($draw - 1) * $length;
            $where = ' 1 = 1 ';
            if ($ispay) {
                $where .= ' AND ispay = ' . $ispay . ' ';
            }
            $where .= ' AND mid = ' . $all['mid'] . ' ';

            $list = GoodsorderModel::getListByWhere($where, $start, $length);
            $count = GoodsorderModel::getCount($where);

            $data = array(
                "returnCode" => 1,
                "returnMsg" => "success!",
                'recordsTotal' => $count,
                'recordsFiltered' => $count,
                'draw' => $draw,
                'data' => $list
            );
            return json($data);
        } else {
            return json([
                "returnCode" => - 2,
                "returnMsg" => "fail!",
                "data" => ""
            ]);
        }
    }

    /**
     * 删除一条
     */
    public function del($id) {
        if (empty($id)) {
            return json([
                "returnCode" => - 6,
                "returnMsg" => "必填参数不能为空!",
                "data" => ""
            ]);
            exit();
        }
        $dataone = GoodsorderModel::selectOneGoodsorderByID($id);
        if ($dataone) {
            $data = GoodsorderModel::delOneGoodsorder($id);
            if ($data) {
                return json([
                    "returnCode" => 1,
                    "returnMsg" => "success!"
                ]);
            } else {
                return json([
                    "returnCode" => - 2,
                    "returnMsg" => "fail!"
                ]);
            }
        } else {
            return json([
                "returnCode" => - 2,
                "returnMsg" => "fail!"
            ]);
        }
    }

    /**
     * 查询一条记录
     */
    public function find($id) {
        $mid = $this->getLoginId();
        $data = GoodsorderModel::selectOneGoodsorderByID($id);
        if (empty($data)) {
            return $this->returnResult(- 1, '订单不存在');
        }
        if ($data['mid'] != $mid) {
            return $this->returnResult(- 1, '无权查看');
        }
        $data['can_cancel'] = $this->_can_cancel($data['status'], $data['flag']);

        if ($data) {
            return json([
                "returnCode" => 1,
                "returnMsg" => "success!",
                "data" => $data
            ]);
        } else {
            return json([
                "returnCode" => - 2,
                "returnMsg" => "fail!"
            ]);
        }
    }

    /**
     * 取消
     */
    public function cancel() {
        $mid = $this->getLoginId();
        $id = $this->request->param('id');
        $order = GoodsorderModel::instance()->find($id);
        if (empty($order)) {
            return $this->returnResult(- 1, '订单不存在');
        }
        if ($order['mid'] != $mid) {
            return $this->returnResult(- 1, '无权限');
        }
        if ($order['ispay'] != 1) { //
            return $this->returnResult(- 1, '订单已经审核,无法取消,请联系客服');
        }

        $cancancel = $this->_can_cancel($order['ispay'], $order['flag']);
        if (! $cancancel) {
            return $this->returnResult(- 1, '订单已备货,无法取消,请联系客服处理!');
        }

        // 更新订单
        $orderUpdate = [
            'id' => $id,
            'ispay' => 2, // 取消
            'updatetime' => Tools::getCurDate()
        ];
        // 修改订单
        GoodsorderModel::instance()->update($orderUpdate);

        $mid = $order['mid']; // 用户id
        $total = floatval($order['total']); // 订单金额
        $num = $order['courier_num'];
        $account = $order['account'];
        $reward_account = $order['reward_account'];
        $goodsId = $order['goodsid'];

        // 修改用户锁定金额,减少锁定,返回账号
        MemberModel::instance()->where('id', $mid)
            ->dec('account_lock', $account)
            ->inc('account', $account)
            ->dec('rewardaccount_lock', $reward_account)
            ->inc('rewardaccount', $reward_account)
            ->update();
        // 更新库存和销售量
        GoodsModel::instance()->where('id', $goodsId)
            ->dec('sales', $num)
            ->inc('stock', $num)
            ->update();

        $member = MemberModel::instance()->find($mid);
        if ($member['openid']) {
            MsgService::sendOrderCancelMsg($member['openid'], $id, $order['oid'], $total);
            MsgService::sendAccountChangeMsg($member['openid'], $total, $order['oid']);
        }

        return $this->returnResult(1, '取消完成');
    }

    private function _can_cancel($ispay = 1, $flag = 0) {

        // 每天 10-以后的订单
        if ($ispay == 1 && $flag == 0) {
            return true;
        }
        return false;
    }

    /**
     * 确认收货
     */
    public function confirm() {
        $mid = $this->getLoginId();
        $id = $this->request->param('id');
        $order = GoodsorderModel::instance()->where([
            'mid' => $mid,
            'id' => $id
        ])->find();

        if (empty($order)) {
            return $this->returnResult(- 1, '订单不存在');
        }
        if ($order['ispay'] != 3) { //
            return $this->returnResult(- 1, '订单未发货,无法确认收货');
        }

        // 更新订单
        $orderUpdate = [
            'id' => $id,
            'ispay' => 5, // 取消
            'updatetime' => Tools::getCurDate()
        ];
        // 修改订单
        $res = GoodsorderModel::instance()->update($orderUpdate);
        if ($res) {
            return $this->returnResult(1, '确认收货成功');
        } else {
            return $this->returnResult(- 1, '');
        }
    }
}